//
//  HYMyBookingVC.m
//  Booking
//
//  Created by Duntech on 2018/4/19.
//  Copyright © 2018年 Duntech. All rights reserved.
//

#import "HYMyBookingVC.h"
#import "HYMyScheduleRoomCell.h"
#import "HYMyBookingSeatCell.h"
#import "HYMyScheduleMeetingRoomModel.h"
#import "HYMyBookingSeatCellModel.h"
#import "HYMyBookingFilterView.h"
#import "HYMyBookingDateSelectView.h"
#import "HYMyBookingRoomDetailVC.h"
#import "HYMyBookingSeatDetailVC.h"
#import "HYMyBookingSwitchView.h"

@interface HYMyBookingVC ()

/** dataSource */
@property (nonatomic,strong) HYTableViewDataSource *dataSource;
/** delegate */
@property (nonatomic,strong) HYTableViewDelegate *delegate;
/** dataSets数据源 */
@property (nonatomic,strong) NSMutableArray *dataSetsArray;
@property (nonatomic,strong) HYMyBookingFilterView *filterView;
@property (nonatomic,strong) HYMyBookingSwitchView *switchView;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,assign) BOOL isShowSelectView;
@property (nonatomic,assign) BOOL isBookingRoomCell;
@property (nonatomic,strong) HYMyBookingDateSelectView *dateCitySelectView;

@property (nonatomic, strong) NSString *status;
@property (nonatomic, strong) NSString *cityId;

@end

@implementation HYMyBookingVC

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.titleView = self.switchView;
    self.isBookingRoomCell = YES;
    [self setupSubViews];
    [self bindingTableViewCell];
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    if (self.isBookingRoomCell) {
        [self requestNetwork];
    }
    else{
        [self requestMyBookingSeats];
    }
}

- (void)setupSubViews{
    
    self.dataSource.dataSource = self.dataSetsArray;
    self.delegate.dataSource = self.dataSetsArray;
    [self.view addSubview:self.filterView];
    [self.view addSubview:self.tableView];
    
    [_filterView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.top.right.equalTo(self.view);
        make.height.mas_equalTo(60 * WIDTH_MULTIPLE);
    }];

    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.filterView.mas_bottom);
    }];
    
    [self.tableView registerClass:[HYMyScheduleRoomCell class] forCellReuseIdentifier:@"HYMyScheduleRoomCell"];
    [self.tableView registerClass:[HYMyBookingSeatCell class] forCellReuseIdentifier:@"HYMyBookingSeatCell"];
}

#pragma mark - network
- (void)requestNetwork{
    NSString *startTime = self.filterView.startTimeLabel.text;
    NSString *endTime = self.filterView.endTimeLabel.text;
    [HYNetRequestHandle getMyScheduleRoomWithCreateBy:[HYUserModel sharedInstance].user.id status:self.status city:self.cityId build:nil floor:nil startTime:startTime endTime:endTime markName:nil meetingroomId:nil Complection:^(NSArray *myScheduleList) {
        
        [self.dataSetsArray removeAllObjects];
        NSMutableArray *sectionArr = [NSMutableArray array];
        [myScheduleList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            HYMyScheduleMeetingRoomModel *model = [HYMyScheduleMeetingRoomModel modelWithDictionary:obj];
            model.cellIdientifier = @"HYMyScheduleRoomCell";
            model.cellHeight = 130 * WIDTH_MULTIPLE;
            [sectionArr addObject:model];
        }];
        [self.dataSetsArray addObject:sectionArr];
        [self.tableView.mj_header endRefreshing];
        [self.tableView reloadData];
    }];
}

- (void)requestMyBookingSeats{
    NSString *startTime = self.filterView.startTimeLabel.text;
    NSString *endTime = self.filterView.endTimeLabel.text;
    [HYNetRequestHandle getMyScheduleSeatWithCreateBy:[HYUserModel sharedInstance].user.id status:self.status startTime:startTime endTime:endTime stationId:nil Complection:^(NSArray *myScheduleList) {
        
        [self.dataSetsArray removeAllObjects];
        NSMutableArray *sectionArr = [NSMutableArray array];
        [myScheduleList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            HYMyBookingSeatCellModel *cellModel = [HYMyBookingSeatCellModel modelWithDictionary:obj];
            cellModel.cellHeight = 100 * WIDTH_MULTIPLE;
            cellModel.cellIdientifier = @"HYMyBookingSeatCell";
            [sectionArr addObject:cellModel];
        }];
        
        [self.dataSetsArray addObject:sectionArr];
        [self.tableView.mj_header endRefreshing];
        [self.tableView reloadData];
    }];
}

- (void)bindingTableViewCell{
    
    __weak typeof(self) weakSelf = self;
    [self.dataSource setBindingCellBlock:^(UITableView *tableView, id rowDataSource, HYBaseTableViewCell *cell, NSIndexPath *indexPath) {
        if (weakSelf.isBookingRoomCell) {
            //会议室的cell
            HYMyScheduleRoomCell *roomCell = (HYMyScheduleRoomCell *)cell;
            roomCell.lookDetailBlock = ^(){
                NSArray *sectionArr = weakSelf.dataSetsArray[0];
                HYMyScheduleMeetingRoomModel *model = sectionArr[indexPath.row];
                HYMyBookingRoomDetailVC *detailVC = [HYMyBookingRoomDetailVC new];
                detailVC.myBookingRoomModel = model;
                [weakSelf.navigationController pushViewController:detailVC animated:YES];
            };
        }
        else{
            //工位的cell
            HYMyBookingSeatCell *seatCell = (HYMyBookingSeatCell *)cell;
            seatCell.lookDetailBlock = ^(){
                NSArray *sectionArr = weakSelf.dataSetsArray[0];
                HYMyBookingSeatCellModel *model = sectionArr[indexPath.row];
                HYMyBookingSeatDetailVC *detailVC = [HYMyBookingSeatDetailVC new];
                detailVC.myBookingSeatModel = model;
                [weakSelf.navigationController pushViewController:detailVC animated:YES];
            };
        }
    }];
    
    [self.delegate setDidSelectedBlock:^(UITableView *tableView, NSIndexPath *indexPath) {
       
        
    }];
    
    [self.delegate setEditActionBlock:^NSArray *(UITableView *tableView, NSIndexPath *indexPath) {
       
        UITableViewRowAction *deleteRoWAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"Delete" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath){
            
        }];
        
        return @[deleteRoWAction];
    }];
    
    [self.dataSource setCellCanEditBlock:^BOOL(UITableView *tableView, NSIndexPath *indexPath) {
        return YES;
    }];
    
    [self.dataSource setCommitEditingBlock:^(UITableView *tableView, UITableViewCellEditingStyle editingStyle, NSIndexPath *indexPath) {
        
        NSMutableArray *sectionArr = weakSelf.dataSetsArray[0];
        
        if (editingStyle == UITableViewCellEditingStyleDelete) {
            
            HYAlertView *alertView = [[HYAlertView alloc] initWithTitle:NSLocalizedString(@"tips", nil) message:NSLocalizedString(@"cancelReservationTips", nil) sureBtn:NSLocalizedString(@"ok", nil) cancleBtn:NSLocalizedString(@"cancel", nil)];
            if (weakSelf.isBookingRoomCell) {
                HYMyScheduleMeetingRoomModel *roomModel = sectionArr[indexPath.row];
                alertView.resultIndex = ^(NSInteger index) {
                    [HYNetRequestHandle cancelMyBookingRoomWithMeetingID:roomModel.id complection:^(BOOL isSuccess) {
                        
                        if (isSuccess) {
                            
                            [sectionArr removeObject:roomModel];
                            [weakSelf.tableView deleteRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationFade];
                        }
                    }];
                };
            }
            else{
                HYMyBookingSeatCellModel *seatModel = sectionArr[indexPath.row];
                alertView.resultIndex = ^(NSInteger index) {
                    [HYNetRequestHandle cancelMyBookingSeatWithSeatID:seatModel.id complection:^(BOOL isSuccess) {
                        
                        if (isSuccess) {
                            
                            [sectionArr removeObject:seatModel];
                            [weakSelf.tableView deleteRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationFade];
                        }
                    }];
                };
            }
            [alertView showAlertView];
        }
        
    }];
}

#pragma mark - emptyDataSource
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView{
    
    if (self.isBookingRoomCell) {
        return [UIImage imageNamed:@"noBook"];
    }
    return [UIImage imageNamed:@"no_seat"];

}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView{
    NSAttributedString *str;
    if (self.isBookingRoomCell) {
        str  = [[NSAttributedString alloc] initWithString:NSLocalizedString(@"noRoomsFound", nil)];
    }
    else{
        str  = [[NSAttributedString alloc] initWithString:NSLocalizedString(@"noSeatsFound", nil)];
    }
    return str;
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{
    return YES;
}

#pragma mark - action
- (void)tapFilterViewAction{
    
    if (!self.isShowSelectView) {
        
        [self.dateCitySelectView showDateCitySelectViewInView:self.view];
    }
    else{
        [self.dateCitySelectView hideDateCitySelectView];
    }
    self.isShowSelectView = !self.isShowSelectView;
}

#pragma mark - lazyload
- (HYTableViewDataSource *)dataSource{
    
    if (!_dataSource) {
        _dataSource = [HYTableViewDataSource new];
    }
    return _dataSource;
}

- (NSMutableArray *)dataSetsArray{
    
    if (!_dataSetsArray) {
        _dataSetsArray = [NSMutableArray array];
    }
    return _dataSetsArray;
}

- (HYTableViewDelegate *)delegate{
    
    if (!_delegate) {
        _delegate = [HYTableViewDelegate new];
    }
    return _delegate;
}

- (HYMyBookingFilterView *)filterView{
    
    if (!_filterView) {
        _filterView = [HYMyBookingFilterView new];
        _filterView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapFilterViewAction)];
        [_filterView addGestureRecognizer:tapGes];
    }
    return _filterView;
}

-(HYMyBookingSwitchView *)switchView{
    if (!_switchView) {
        _switchView = [[HYMyBookingSwitchView alloc] initWithItemTitles:@[NSLocalizedString(@"room", nil), NSLocalizedString(@"seat", nil)]];
        _switchView.frame = CGRectMake(0, 0, 175, 35);
        [_switchView clickDefault];
        kWeakSelf(weakSelf);
        _switchView.NHCustomSegmentViewBtnClickHandle = ^(HYMyBookingSwitchView *switchView, NSString *title, NSInteger currentIndex) {
            if (currentIndex == 0) {
                [weakSelf requestNetwork];
                weakSelf.isBookingRoomCell = YES;
            }
            else{
                [weakSelf requestMyBookingSeats];
                weakSelf.isBookingRoomCell = NO;
            }
        };
    }
    return _switchView;
}

- (HYMyBookingDateSelectView *)dateCitySelectView{
    
    if (!_dateCitySelectView) {
        
        _dateCitySelectView = [HYMyBookingDateSelectView new];
        _dateCitySelectView.viewController = self;
        __weak typeof(self) weakSelf = self;
        _dateCitySelectView.MyBookingFilterSearchBlock = ^(NSString *startTime, NSString *endTime, NSInteger status, NSString *cityID, NSString *city) {
            
            NSDate *startDate = [NSDate dateWithString:startTime format:@"yyyy-MM-dd HH:mm"];
            NSDate *endDate = [NSDate dateWithString:endTime format:@"yyyy-MM-dd HH:mm"];
            NSString *startDateStr = [HYDateHandle getDateStringWithDate:startDate formater:@"yyyy-MM-dd"];
            NSString *endDateStr = [HYDateHandle getDateStringWithDate:endDate formater:@"yyyy-MM-dd"];
            weakSelf.filterView.startTimeLabel.text = startDateStr;
            weakSelf.filterView.endTimeLabel.text = endDateStr;
            if (city) {
                weakSelf.cityId = cityID;
                weakSelf.filterView.officeLabel.text = city;
            }
            if (status == 0) {
                weakSelf.status = @"1";
                weakSelf.filterView.statusLabel.text = NSLocalizedString(@"confirmStatus", nil);
            }
            else if (status == 1){
                weakSelf.status = @"2";
                weakSelf.filterView.statusLabel.text = NSLocalizedString(@"currentStatus", nil);
            }
            else if (status == 2){
                weakSelf.status = @"3";
                weakSelf.filterView.statusLabel.text = NSLocalizedString(@"expiredStatus", nil);
            }
            else{
                weakSelf.status = nil;
                weakSelf.filterView.statusLabel.text = NSLocalizedString(@"allBookings", nil);
            }
            
            if (weakSelf.isBookingRoomCell) {
                [weakSelf requestNetwork];
            }
            else{
                [weakSelf requestMyBookingSeats];
            }
        };
    }
    return _dateCitySelectView;
}

- (UITableView *)tableView{
    
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.backgroundColor = KAPP_TableView_BgColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self.delegate;
        _tableView.dataSource = self.dataSource;
        _tableView.emptyDataSetSource = self;
        _tableView.emptyDataSetDelegate = self;
        __weak typeof(self) weakSelf = self;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
          
            if (weakSelf.isBookingRoomCell) {
                [weakSelf requestNetwork];
            }
            else{
                [weakSelf requestMyBookingSeats];
            }
        }];
    }
    return _tableView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
